/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package ejb;

import entities.Category;
import entities.Product;
import java.util.List;
import javax.ejb.Stateless;
import javax.persistence.EntityManager;
import javax.persistence.NoResultException;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;

/**
 *
 * @author ervaka
 */
@Stateless
public class ProductBean implements ProductBeanLocal {

    @PersistenceContext(unitName = "Tiendalia-ejbPU")
    private EntityManager em;

    @Override
    public Product insert(Product product) {
        return update(product);
    }

    @Override
    public Product update(Product product) {
        return em.merge(product);
    }

    @Override
    public List<Product> findAll() {
        Query query = em.createNamedQuery("Product.findAll");
        return query.getResultList();
    }

    @Override
    public Product findById(Long productId) {
        Product product;
        Query query = em.createNamedQuery("Product.findById");
        query.setParameter("id", productId);
        try {
            product = (Product) query.getSingleResult();
        } catch (NoResultException e) {
            product = null;
        }
        return product;
    }

    @Override
    public Product findByName(String productName) {
        Product product;
        Query query = em.createNamedQuery("Product.findByName");
        query.setParameter("name", productName);
        try {
            product = (Product) query.getSingleResult();
        } catch (NoResultException e) {
            product = null;
        }
        return product;
    }

    @Override
    public List<Product> findByCategory(Category category) {
        if (category == null) {
            return findAll();
        } else {
            Query query = em.createNamedQuery("Product.findByCategory");
            query.setParameter("category", category);
            return query.getResultList();
        }

    }
    // Add business logic below. (Right-click in editor and choose
    // "Insert Code > Add Business Method")

    @Override
    public List<Product> findAllLike(String input) {
        Query query = em.createNamedQuery("Product.findAllLike");
        query.setParameter("input", "%" + input + "%");
        return query.getResultList();
    }
}
